/* 
 * Copyright (C) 2014 Oliver Goetze
 * 
 * This file is part of Squared Battery Widget, especially made to use with buzz launcher 
 * (grid 12x10), and a 720x1280px xhdpi display. others may also work, untested...  
 * reason was, that I found no battery widget that fit my squarish needs ;) so i decided to
 * create my own widget...but from scratch is very stressy as beginner, so a cheer 
 * to free software! 
 * 
 * (many apologies for my not existent english grammar :>)
 * 
 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 * This file was part of Simple Lightweight Battery Widget (SWLBattery Widget),
 * and was modified by me, Oliver Goetze, under the terms of the GNU GPLv3, as 
 * recommended by original author Christian Schneider.
 * original source code: https://code.google.com/p/slw-battery-widget/
 * Thanks to Christian Schneider, your code "saved me a lot of time" :)
 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!   
 *  
 * Squared Battery Widget is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Squared Battery Widget is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Squared Battery Widget. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package de.n3bu.squaredbatterywidget;

import java.util.Locale;

import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

/*
 * set layout, colors and other options to squared battery widget
 * or use the shortcut to system battery usage... 
 */
public class SettingsActivity extends Activity {

	private int mAppWidgetId;

	private RadioGroup radioGroupLayout;
	private RadioButton radioLayoutButton;

	private Button resetColorsButton;

	private EditText textColorEt;

	private EditText p100ColorEt;

	private EditText p90ColorEt;

	private EditText p80ColorEt;

	private EditText p70ColorEt;

	private EditText p60ColorEt;

	private EditText p50ColorEt;

	private EditText p40ColorEt;

	private EditText p30ColorEt;

	private EditText p20ColorEt;

	private EditText p10ColorEt;

	private EditText chargingColorEt;

	private Button batteryUsageButton;

	private Button okButton;
	
	private CheckBox showPercentText;
	
	
	private void checkEditText(EditText et) {
		final String hex = "#" + et.getText().toString().toUpperCase(Locale.getDefault());
		try {
			final int color = Color.parseColor(hex);			
			et.setBackgroundColor(color);
			
			if(hasDarkBackgroundColor(et))
				et.setTextColor(getResources().getColor(R.color.white_opak));
			else
				et.setTextColor(getResources().getColor(R.color.black));
			
			okButton.setEnabled(true);
		} catch (Exception e) {
			
			// no valid color => do not refresh bg color preview
			// instead, show error colors an disable ok button
			et.setTextColor(getResources().getColor(R.color.yellow));
			et.setBackgroundColor(getResources().getColor(R.color.error));
			okButton.setEnabled(false);
		}
	}
	
	/**
	 * {@link http://en.wikipedia.org/wiki/Luminance_%28relative%29}
	 * @param et the edittext which bg will be checked for dark color
	 * @return true if the bg color of et is dark 
	 */
	
	private boolean hasDarkBackgroundColor(EditText et) {
		final int color;
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) 
			color = ((ColorDrawable) et.getBackground()).getColor();
		else
			return false; //"older device"-users have to select bright colors at the moment :/
					      //TODO: is there another way to obtain edittexts bg color < HONEYCOMP???
						  //use black text with tiny white border in all edittexts instead!?	
		
		final int r = Color.red(color);
		final int g = Color.green(color);
		final int b = Color.blue(color);
		final float lum = r * 0.2126f + g * 0.7152f + b * 0.0722f;
		if(lum < 50) // def.: < 50 is "dark" (at least for me..too dark to recognize black text^^)
			return true;		
		return false;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settingsactivitylayout);
		
		final TextView tvColorPickerUrl = (TextView) findViewById(R.id.colorsinfolabelrecUrl);
		tvColorPickerUrl.setMovementMethod(LinkMovementMethod.getInstance());

		final Intent intent = getIntent();
		final Bundle extras = intent.getExtras();
		if (extras != null) {
			mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
		}

		showPercentText = (CheckBox) findViewById(R.id.showPercentTextCB);
		showPercentText.setChecked(Helper.readShowPercentText(getApplicationContext()));
		
		radioGroupLayout = (RadioGroup) findViewById(R.id.radioLayoutGroup);
		int layout = Helper.readLayout(this);
		switch (layout) {
		case Helper.LAYOUT_1X1:
			((RadioButton) findViewById(R.id.radio_layout_1x1)).setChecked(true);
			break;
		case Helper.LAYOUT_4X4:
			((RadioButton) findViewById(R.id.radio_layout_4x4)).setChecked(true);
			break;
		case Helper.LAYOUT_RING:
			((RadioButton) findViewById(R.id.radio_layout_ring)).setChecked(true);
			break;
		}
		
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) 
			((RadioButton) findViewById(R.id.radio_layout_ring)).setEnabled(false);
		
		chargingColorEt = (EditText) findViewById(R.id.chargingcoloredit);
		chargingColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(chargingColorEt);
			}
		});
		p10ColorEt = (EditText) findViewById(R.id.p10coloredit);
		p10ColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(p10ColorEt);
			}
		});
		p20ColorEt = (EditText) findViewById(R.id.p20coloredit);
		p20ColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(p20ColorEt);
			}
		});
		p30ColorEt = (EditText) findViewById(R.id.p30coloredit);
		p30ColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(p30ColorEt);
			}
		});
		p40ColorEt = (EditText) findViewById(R.id.p40coloredit);
		p40ColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(p40ColorEt);
			}
		});
		p50ColorEt = (EditText) findViewById(R.id.p50coloredit);
		p50ColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(p50ColorEt);
			}
		});
		p60ColorEt = (EditText) findViewById(R.id.p60coloredit);
		p60ColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(p60ColorEt);
			}
		});
		p70ColorEt = (EditText) findViewById(R.id.p70coloredit);
		p70ColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(p70ColorEt);
			}
		});
		p80ColorEt = (EditText) findViewById(R.id.p80coloredit);
		p80ColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(p80ColorEt);
			}
		});
		p90ColorEt = (EditText) findViewById(R.id.p90coloredit);
		p90ColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(p90ColorEt);
			}
		});
		p100ColorEt = (EditText) findViewById(R.id.p100coloredit);
		p100ColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(p100ColorEt);
			}
		});

		textColorEt = (EditText) findViewById(R.id.textcoloredit);
		textColorEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				checkEditText(textColorEt);				
			}
		});

		final Activity a = this;
		
		resetColorsButton = (Button) findViewById(R.id.resetColorsButton);
		resetColorsButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Helper.resetColors(a);
				setEditTextColors();
			}
		});
		
		batteryUsageButton = (Button) findViewById(R.id.btBatteryUsage);
		batteryUsageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				final Intent ibu = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
				startActivity(ibu);
			}
		});

		okButton = (Button) findViewById(R.id.btOk);
		okButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {	
				
				//prepare the widget to be clickable...
				final Intent intent = new Intent(getBaseContext(),
						SettingsActivity.class);
				intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);				
				intent.setData(Uri.parse("tel:/" + (int)System.currentTimeMillis()));				
				final PendingIntent pendingIntent = PendingIntent.getActivity(
						getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);				
				final AppWidgetManager appWidgetManager = AppWidgetManager
						.getInstance(getBaseContext());
				
				//set layout based on users choice...and set widget clickable...
				final int selectedOption = radioGroupLayout.getCheckedRadioButtonId();				
			    radioLayoutButton = (RadioButton) findViewById(selectedOption);
			    final String selectedOptionText = radioLayoutButton.getText().toString();
				Toast.makeText(SettingsActivity.this, selectedOptionText, Toast.LENGTH_LONG).show();
				
				final boolean isShowPercentText = showPercentText.isChecked();
				Helper.writeShowPercentText(a, isShowPercentText);				
				
				RemoteViews views = null;
				if(selectedOptionText.equals(getResources().getString(R.string.radio_layout_1x1_label))) {
					Helper.writeLayout(a, Helper.LAYOUT_1X1);
					views = new RemoteViews(getBaseContext()
							.getPackageName(), R.layout.simple);			
					views.setOnClickPendingIntent(R.id.tvCenterVg,
							pendingIntent);
					if(isShowPercentText) 
						views.setTextViewText(R.id.tvCenterVg, "%"); //initially, instead of show nothing
				}
				if(selectedOptionText.equals(getResources().getString(R.string.radio_layout_4x4_label))) {
					Helper.writeLayout(a, Helper.LAYOUT_4X4);
					views = new RemoteViews(getBaseContext()
							.getPackageName(), R.layout.main);			
					views.setOnClickPendingIntent(R.id.TextViewCenter,
							pendingIntent);
					if(isShowPercentText) 
						views.setTextViewText(R.id.TextViewCenter, "%"); //initially, instead of show nothing
				}
				if(selectedOptionText.equals(getResources().getString(R.string.radio_layout_ring))) {
					Helper.writeLayout(a, Helper.LAYOUT_RING);
					views = new RemoteViews(getBaseContext()
							.getPackageName(), R.layout.gridlayout);			
					views.setOnClickPendingIntent(R.id.TextViewCenterGl,
							pendingIntent);
					if(isShowPercentText) 
						views.setTextViewText(R.id.TextViewCenterGl, "%"); //initially, instead of show nothing
				}

				if(views != null)
					appWidgetManager.updateAppWidget(mAppWidgetId, views);					
				
				//write all set colors (if an user types a wrong color code,
				//the ok button will be disabled immediately...)
				try {
					Helper.writeColor(
							a, Helper.CHARGING,
							Color.parseColor("#" + 
							chargingColorEt.getText().toString()));
					
					Helper.writeColor(a, Helper.COLOR_10_00,
							Color.parseColor("#" + p10ColorEt.getText().toString()));
					Helper.writeColor(a, Helper.COLOR_20_00,
							Color.parseColor("#" + p20ColorEt.getText().toString()));
					Helper.writeColor(a, Helper.COLOR_30_00,
							Color.parseColor("#" + p30ColorEt.getText().toString()));
					Helper.writeColor(a, Helper.COLOR_40_00,
							Color.parseColor("#" + p40ColorEt.getText().toString()));
					Helper.writeColor(a, Helper.COLOR_50_00,
							Color.parseColor("#" + p50ColorEt.getText().toString()));
					Helper.writeColor(a, Helper.COLOR_60_00,
							Color.parseColor("#" + p60ColorEt.getText().toString()));
					Helper.writeColor(a, Helper.COLOR_70_00,
							Color.parseColor("#" + p70ColorEt.getText().toString()));
					Helper.writeColor(a, Helper.COLOR_80_00,
							Color.parseColor("#" + p80ColorEt.getText().toString()));
					Helper.writeColor(a, Helper.COLOR_90_00,
							Color.parseColor("#" + p90ColorEt.getText().toString()));
					Helper.writeColor(a, Helper.COLOR_100_00, Color.parseColor("#"
							+ p100ColorEt.getText().toString()));

					Helper.writeColor(a, Helper.TEXTCOLOR, Color.parseColor("#"
							+ textColorEt.getText().toString()));
				} catch (Exception e) {
					//one color not parsable as color (can actually not happen...)
					//do nothing
				}
				
				//infom the widget and close current SettingsActivity
				final Intent resultValue = new Intent();
				resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
						mAppWidgetId);
				setResult(RESULT_OK, resultValue);		
				
				a.finish();
			}
		});
		setEditTextColors();
		
		// otherwise an user will be prompted to enter text...annoying
		batteryUsageButton.requestFocus(); 
	}
	
	private void setEditTextColors() {
		int color = Helper.readColor(this, Helper.CHARGING);
		chargingColorEt.setText(Integer.toHexString(color));
		chargingColorEt.setBackgroundColor(color);

		color = Helper.readColor(this, Helper.COLOR_10_00);
		p10ColorEt.setText(Integer.toHexString(color));
		p10ColorEt.setBackgroundColor(color);
		color = Helper.readColor(this, Helper.COLOR_20_00);
		p20ColorEt.setText(Integer.toHexString(color));
		p20ColorEt.setBackgroundColor(color);
		color = Helper.readColor(this, Helper.COLOR_30_00);
		p30ColorEt.setText(Integer.toHexString(color));
		p30ColorEt.setBackgroundColor(color);
		color = Helper.readColor(this, Helper.COLOR_40_00);
		p40ColorEt.setText(Integer.toHexString(color));
		p40ColorEt.setBackgroundColor(color);
		color = Helper.readColor(this, Helper.COLOR_50_00);
		p50ColorEt.setText(Integer.toHexString(color));
		p50ColorEt.setBackgroundColor(color);
		color = Helper.readColor(this, Helper.COLOR_60_00);
		p60ColorEt.setText(Integer.toHexString(color));
		p60ColorEt.setBackgroundColor(color);
		color = Helper.readColor(this, Helper.COLOR_70_00);
		p70ColorEt.setText(Integer.toHexString(color));
		p70ColorEt.setBackgroundColor(color);
		color = Helper.readColor(this, Helper.COLOR_80_00);
		p80ColorEt.setText(Integer.toHexString(color));
		p80ColorEt.setBackgroundColor(color);
		color = Helper.readColor(this, Helper.COLOR_90_00);
		p90ColorEt.setText(Integer.toHexString(color));
		p90ColorEt.setBackgroundColor(color);
		color = Helper.readColor(this, Helper.COLOR_100_00);
		p100ColorEt.setText(Integer.toHexString(color));
		p100ColorEt.setBackgroundColor(color);

		color = Helper.readColor(this, Helper.TEXTCOLOR);
		textColorEt.setText(Integer.toHexString(color));
		textColorEt.setBackgroundColor(color);
	}
}
